package controllers;

import java.util.LinkedList;
import java.util.List;

import play.db.jpa.JPA;
import play.mvc.Controller;

import model.Player;

public class PlayerRegistry extends Controller {
	private List<Player> activePlayer;
	private Thread timeoutPlayers;
	static private PlayerRegistry instance;
	
	private PlayerRegistry() {
		activePlayer = new LinkedList<Player>();
		timeoutPlayers = new TimeoutThread(activePlayer);
		timeoutPlayers.start();
	}
	
	static public PlayerRegistry getInstance() {
		if (instance == null) instance = new PlayerRegistry();
		return instance;
	}
	
	public Player createPlayer(String name, String login, String passwd, String email) {
		Player p= new Player(name, login, passwd, email);
		
		if (p.save()) {
			return p;
		} else return null;
	}
	
	public Player login(String login, String passwd) {
		Player p = JPA.em().find(Player.class, login);
		if (p.getPasswd().compareTo(passwd)==0) {
			return p;
		}
		else return null; 
	}
	
	public Player findPlayer(String login) {
		return JPA.em().find(Player.class, login);
	}
	
	private class TimeoutThread extends Thread {
		private List<Player> monitoring;
		
		public TimeoutThread(List<Player> l) {
			monitoring = l;
		}
		
		@Override
		public void run() {
			for (Player p : monitoring) {
				if (p.getLastAction() == 0) {
					monitoring.remove(p); // remove p se a atividade estiver em zero
				} else {
					p.lastActionDecrease(); // decrementa o last action
				}
			}
			try { // por segurança, para evitar interrupções
				sleep(1000); // sleep por 1 segundo
			} catch (InterruptedException e) {
			} 
		}
	}
}
